<?php
namespace app\index\controller;
use think\Db;
use think\Session;

class Index
{

    public function index()
    {
        $eid = isset($_GET['id'])?$_GET['id']:false;
        $appid = 'wxc54c32f29c629322';
        $appsecret = 'be73f1395f72be3ff6e7dfcf9ec20be0';
        $scope = 'snsapi_userinfo';
        $website = 'http://www.cssw3c.com/management/public/';
        $redirect_uri = 'http://www.cssw3c.com/management/public/';
        $jssdk = new JSSDK("$appid", "$appsecret");
        $signPackage = $jssdk->GetSignPackage();
        $data['appId'] = $signPackage['appId'];
        $data['timestamp'] = $signPackage['timestamp'];
        $data['nonceStr'] = $signPackage['nonceStr'];
        $data['signature'] = $signPackage['signature'];
        if(empty(session("openid"))){
            $code = isset($_GET['code'])?$_GET['code']:false;
            if($eid){
                $redirect_uri =$redirect_uri."?id=".$eid;
            }
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=$scope&state=STATE#wechat_redirect";
            if(!$code){
                header("Location:$url");
            }else{
                $url_code = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
                $code_obj = json_decode(file_get_contents($url_code));
                  if(!isset($code_obj->errcode)){
                    $access_token = $code_obj->access_token;
                    $openid = $code_obj->openid;
                    $url_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
                    $userinfo_obj = json_decode(file_get_contents($url_userinfo));
                    if(!isset($userinfo_obj->errcode)){
                        session("openid",$userinfo_obj->openid);
                        session('nickname',$userinfo_obj->nickname);
                        session('sex',$userinfo_obj->sex);
                        session('province',$userinfo_obj->province);
                        session('city',$userinfo_obj->city);
                        session('country',$userinfo_obj->country);
                        session('headimgurl',$userinfo_obj->headimgurl);

                        $data['id'] = session('openid');
                        $data['nickname'] = session('nickname');
                        $data['sex'] = session('sex');
                        $data['province'] = session('province');
                        $data['city'] = session('city');
                        $data['country'] = session('country');
                        $data['headimgurl'] = session('headimgurl');
                        $data['friendeventid'] = '';
                        $data['eventid'] = '';
                        $data['eventusername'] = '';
                        $event = Db::name('event')->where('id',1)->value('event_status');
                        if($eid){
                            $user = Db::name('event_action')
                            ->where('id',$eid)
                            ->where('status',1)
                            ->find();
                            if(!empty($user)){
                                if($user['userid']==session('openid')){
                                    header("Location:$website");
                                }
                            }else{
                                header("Location:$website");
                            }
                            $friendevent = Db::name('event_action')
                            ->where('eventid',1)
                            ->where('userid',session('openid'))
                            ->where('status',1)
                            ->find();
                            if(!empty($friendevent)){
                                $data['friendeventid'] = $friendevent['id'];
                            }
                        }else{
                            $user = Db::name('event_action')
                            ->where('eventid',1)
                            ->where('userid',$userinfo_obj->openid)
                            ->where('status',1)
                            ->find();
                        }

                        $data['friends'] = '';
                        if(!empty($user)){
                            $data['eventid'] = $user['id'];
                            $data['eventusername'] =$user['username'];
                            if($user['event_number']>0){
                                $firends = Db::name('event_friends')
                                ->where('event_action_id',$user['id'])
                                ->where('status',1)
                                ->select();
                                foreach ($firends as $key => $value) {
                                    $data['friends'][$key]['id'] = $value['seatid'];
                                    $data['friends'][$key]['wxid'] = $value['userid'];
                                    $data['friends'][$key]['name'] = $value['username'];
                                }
                                $data['friends'] = json_encode($data['friends']);
                            }
                        }
                        if($event=='1'){
                            //活动正在进行中
                             if(empty($user)){
                                //可以发起
                                $data['eventStatus'] =1;
                             }else if($user['status']==1){
                                //正在进行中
                                $data['eventStatus'] =2;
                             }else if($user['status']==2){
                                //已获得
                                $data['eventStatus'] =3;
                             }
                        }else if($event=='2'){
                            //活动名额已抢完
                            if($user['status']==2){
                                //已获得
                                $data['eventStatus'] =3;
                             }else{
                                //活动已结束
                                $data['eventStatus'] =4;
                             }

                        }else if($event=='3'){
                            //活动已结束
                            $data['eventStatus'] =4;
                        }
                        return view('index',$data);

                    }else{
                        //拉取用户信息失败
                        header("Location:$url");
                    }
                  }else{
                    //授权错误
                    header("Location:$url");
                  }
            }
        }else{
            $data['id'] = session('openid');
            $data['nickname'] = session('nickname');
            $data['sex'] = session('sex');
            $data['province'] = session('province');
            $data['city'] = session('city');
            $data['country'] = session('country');
            $data['headimgurl'] = session('headimgurl');
            $data['friendeventid'] = '';
            $data['eventid'] = '';
            $data['eventusername'] = '';
            $event = Db::name('event')->where('id',1)->where('status',1)->value('event_status');
            if($eid){
                $user = Db::name('event_action')
                ->where('id',$eid)
                ->where('status',1)
                ->find();
                if(!empty($user)){
                    if($user['userid']==session('openid')){
                        header("Location:$website");
                    }
                }else{
                    header("Location:$website");
                }
                $friendevent = Db::name('event_action')
                ->where('eventid',1)
                ->where('userid',session('openid'))
                ->where('status',1)
                ->find();
                if(!empty($friendevent)){
                    $data['friendeventid'] = $friendevent['id'];
                }
            }else{
                $user = Db::name('event_action')
                ->where('eventid',1)
                ->where('userid',session('openid'))
                ->where('status',1)
                ->find();
            }

            $data['friends']='';
            if(!empty($user)){
                $data['eventid'] = $user['id'];
                $data['eventusername'] =$user['username'];
                if($user['event_number']>0){
                    $firends = Db::name('event_friends')
                    ->where('event_action_id',$user['id'])
                    ->where('status',1)
                    ->select();
                    foreach ($firends as $key => $value) {
                        $data['friends'][$key]['id'] = $value['seatid'];
                        $data['friends'][$key]['wxid'] = $value['userid'];
                        $data['friends'][$key]['name'] = $value['username'];
                    }
                    $data['friends'] = json_encode($data['friends']);
                }
            }
            if($event=='1'){
                //活动正在进行中
                 if(empty($user)){
                    //可以发起
                    $data['eventStatus'] =1;
                 }else if($user['event_status']==1){
                    //正在进行中
                    $data['eventStatus'] =2;

                 }else if($user['event_status']==2){
                    //已获得
                    $data['eventStatus'] =3;
                 }
            }else if($event=='2'){
                //活动名额已抢完
                if($user['event_status']==2){
                    //已获得
                    $data['eventStatus'] =3;
                 }else{
                    //活动已结束
                    $data['eventStatus'] =4;
                 }

            }else if($event=='3'){
                //活动已结束
                $data['eventStatus'] =4;
            }
            return view('index',$data);
        }
    }

    public function addEvent()
    {
        $data = ['name'=>'江西银行派对活动','description'=>'江西银行派对活动','status'=>'1'];
        Db::name('event')->insert($data);
    }

    public function eventStart()
    {
        $eventStatus = Db::name('event')->where('id',1)->where('status',1)->value('event_status');
        if($eventStatus==1){
            //活动正在进行
            $data = ['eventid'=>1,'userid'=>session('openid'),'username'=>session('nickname'),'event_status'=>1,'status'=>1];
            $user = Db::name('event_action')->insertGetId($data);
            if(!empty($user)){
                $dataRespose = ['resultCode'=>'0','msg'=>'发起成功','id'=>"$user"];
            }else{
                $dataRespose = ['resultCode'=>'1','msg'=>'发起失败'];
            }
        }else{
            $dataRespose = ['resultCode'=>'2','msg'=>'活动不在进行中'];
        }

        return json($dataRespose);
    }

    public function eventJoin()
    {
        $id = $_POST['id'];
        $seatid = $_POST['seatid'];

        $even = Db::name('event')->where('id',1)->where('status',1)->find();
        $event_action = Db::name('event_action')->where('id',$id)->where('status',1)->find();

        if(($even['event_status']==1)&&($even['event_num']<$even['total'])&&($event_action['event_status']==1)&&($event_action['event_number']<$even['event_limit'])){
            //更新event_action表
            if($event_action['event_number'] == $even['event_limit']-1){
                $data_action = [
                    'event_number'=>$event_action['event_number']+1,
                    'event_status'=>2
                ];
                $update_event_action = Db::name('event_action')->where('id',$id)->where('status',1)->update($data_action);
                if($update_event_action){
                    //更新event表
                    $even_temp = Db::name('event')->where('id',1)->where('status',1)->find();
                    if(($even_temp['event_status']==1)&&($even_temp['event_num'] < $even_temp['total'])){
                        if($even_temp['event_num'] == $even_temp['total']-1){
                            $data_event = [
                                'event_num'=>$even['event_num']+1,
                                'event_status'=>2
                            ];
                            $update_event = Db::name('event')->where('id',1)->where('status',1)->update($data_event);
                        }else{
                            $update_event = Db::name('event')->where('id',1)->where('status',1)->setInc('event_num');
                        }
                        if($update_event){
                            $data_friends =[
                                'event_action_id'=>$id,
                                'userid'=>session('openid'),
                                'seatid'=>$seatid,
                                'username'=>session('nickname'),
                                'status'=>1
                            ];
                            $update_friends = Db::name('event_friends')->insertGetId($data_friends);
                            if($update_friends){
                                $dataRespose = ['resultCode'=>'0','msg'=>'发起成功'];
                            }else{
                                $dataRespose = ['resultCode'=>'6','msg'=>'参加用户表插入数据错误'];
                            }
                        }else{
                            $dataRespose = ['resultCode'=>'5','msg'=>'活动主表更新出错'];
                        }
                    }else{
                        $dataRespose = ['resultCode'=>'4','msg'=>'活动主表状态异常'];
                    }
                }else{
                    $dataRespose = ['resultCode'=>'3','msg'=>'活动发起表更新异常'];
                }
            }else{
                $update_event_action = Db::name('event_action')->where('id',$id)->where('status',1)->setInc('event_number');
                if($update_event_action){
                    $data_friends =[
                        'event_action_id'=>$id,
                        'userid'=>session('openid'),
                        'seatid'=>$seatid,
                        'username'=>session('nickname'),
                        'status'=>1
                    ];
                    $update_friends = Db::name('event_friends')->insertGetId($data_friends);
                    if($update_friends){
                        $dataRespose = ['resultCode'=>'0','msg'=>'发起成功'];
                    }else{
                        $dataRespose = ['resultCode'=>'6','msg'=>'参加用户表插入数据错误'];
                    }
                }else{
                    $dataRespose = ['resultCode'=>'1','msg'=>'活动发起表更新异常'];
                }
            }
        }else{
            $dataRespose = ['resultCode'=>'2','msg'=>'活动数据异常'];
        }

        return json($dataRespose);
    }

    public function verifyWeixinSSO()
    {
        if(session("openid")){
            $data = [
                'resultCode'=>'0',
                'msg'=>'成功',
                'id'=>session("openid"),
                'nickname'=>session('nickname'),
                'sex'=>session('sex'),
                'province'=>session('province'),
                'city'=>session('city'),
                'country'=>session('country'),
                'headimgurl'=>session('headimgurl')
            ];
        }else{
            $data = [
                'resultCode'=>'1',
                'msg'=>'获取用户信息失败'
            ];
        }
        return json($data);
    }
}
